package com.wochao.web.admin.custom.converter;

import com.wochao.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * 自定义的ConverterFactory，用于通用的枚举类型转换
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
//                //获取枚举实例对象
//                Enum.class.getEnumConstants();
//                //或：
//                Enum.values();
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                for (T enumConstant:targetType.getEnumConstants()){
                    if(enumConstant.getCode().equals(Integer.valueOf(code))){
                        return enumConstant;
                    }
                }throw new IllegalArgumentException("code:" + code + "非法");
            }
        };
    }
}
